

/**
 * 栈  LIFO一般指后进先出法
 * 使用数组存储
 */
export class Stack<T>{

    private _items: T[];

    public constructor() {
        this._items = [];
    }

    /**添加新元素 */
    public push(ele: T) {
        this._items.push(ele);
    }

    /**移除栈顶元素 */
    public pop() {
        return this._items.pop();
    }

    /**返回栈顶元素,但不对栈做任何修改 */
    public peek() {
        return this._items[this._items.length - 1];
    }

    /**
     * 判断栈是否还有元素存在 
     */
    public isEmpty() {
        return this._items.length === 0;
    }

    /**
     * 移除栈里面的所有元素
     */
    public clear() {
        // this._items = [];
        this._items.length = 0;
    }

    public toString() {
        if (this.isEmpty()) {
            return '';
        }

        let objStr = `${this._items[0]}`;
        for (let i = 1; i < this.length; i++) {
            objStr = `${objStr},${this._items[i]}`;
        }
        return objStr;
    }


    /**
     * 返回栈里面的元素个数
     */
    public get length() {
        return this._items.length;
    }
}


/**
 * 栈  LIFO一般指后进先出法
 * 使用对象存储
 */
export class Stack2 {
    private _items: any
    private _length: number;

    public constructor() {
        this._length = 0;
        this._items = {};
    }

    public push(element: any) {
        this._items[this._length] = element;
        this._length++;
    }

    public pop() {
        if (this.isEmpty()) {
            return undefined;
        }
        this._length--;
        const result = this._items[this._length];
        delete this._items[this._length];
        return result;
    }

    public peek() {
        if (this.isEmpty()) {
            return undefined;
        }
        return this._items[this._length - 1];
    }

    public clear() {
        this._items = {};
        this._length = 0;
    }

    public isEmpty() {
        return this.length === 0;
    }

    public get length() {
        return this._length;
    }

}